<template>
	<view class="content">
		<z-paging ref="paging" :auto="false" :default-page-size="20" v-model="filterResult" @query="getSearchList">
			<template #top>
				<u-navbar :fixed="false" :title="pageParam.name +'筛选'" :autoBack="true" :safeAreaInsetTop="true"
					leftIconColor="#fff">
				</u-navbar>

				<view class="SearchBox" v-if="showSearch">
					<u-search :showAction="true" v-model="filterData[searchKey]" @search="search" @custom="SearchOrAdd"
						shape="square" :actionText="AllowAddEdit ? '+' :'查询'"
						:actionStyle="{color:'#fff',fontSize: AllowAddEdit ? '40px' : '16px'}"
						:animation="false"></u-search>
				</view>
				<view style="padding:10px;border-bottom: 1px solid #ebebeb;" v-if="parentValue">
					<u-icon name="arrow-down" :label="typeName" labelPos="left"
						style="display: flex;justify-content: center;" @click="openChooseType"></u-icon>
				</view>
			</template>
			<view class="MainBox">
				<u-cell v-for="(item, index) in filterResult" :key="index" :title="item[displayValue]" size="large"
					:clickable="true" @click="ChoiceCell(item)">
					<!-- <template #label>
						<view
							v-if="pageParam && pageParam.serverSearch.subText && pageParam.serverSearch.subText.length">

							<view v-for="DecsItem in pageParam.serverSearch.subText">
								<view v-if="item[DecsItem.labelKey]"
									style="font-size: 14px;color: #999;margin-top: 4px;">
									{{DecsItem.label}} {{item[DecsItem.labelKey]}}
								</view>
							</view>
						</view>
					</template>

					<template #value>
						<view v-if="item.checked">
							<u-icon size="30" name="checkbox-mark" color="#12ce04"></u-icon>

						</view>
					</template> -->
				</u-cell>
			</view>

		</z-paging>
		<next-tree :selectParent="true" :checkStrictly="true" funcMode="checkbox" ref="nextTreeAsyncRef"
			:expandedKeys="expandNodes" :treeData="treeData" :themeColor="treeThemeColor" :cancelColor="treeThemeColor"
			:titleColor="treeThemeColor" @confirm="onTreeConfirm"></next-tree>

	</view>
</template>

<script>
	/* 新建工单 */
	export default {
		data() {
			return {
				pickerListen: 'selectPicker',
				ShowLoadingmore: true,
				IsLocalData: false, // 判断是否为本地数据
				showSearch: false,
				searchKey: '', // 接口请求关键字
				listAllData: [], // 测试列表总数据
				searchValue: '', // 搜索框数据
				ListData: [], // 列表数据
				status: 'loadmore',
				page: {
					pageIndex: 1, // 页码
					pageSize: 30, // 每页数量 
				},
				pageParam: {}, // 页面传递的参数
				AllowAddEdit: false, // 是否允许新增编辑
				sql: '',
				displayValue: '',
				hiddenValue: '',
				parentValue: '',
				filterData: {},
				treeQuery: ' 1=1 ',
				treeDataSource: '',
				treeDisplayValue: '',
				treeHiddenValue: '',
				treeParentValues: '',
				chooseType: '',
				filterResult: [],
				treeThemeColor: '#51d0d0',
				treeData: [],
				expandNodes: [],
				typeName: '分类筛选',
				filterSQL: '',
				formSQL: ''

			}
		},
		created() {},
		onShow() {},
		async onLoad(option) {
			var that = this;
			if (!this.$utils.isEmpty(option)) {
				this.pickerListen = option.pickerListen
			}

			var selectPickerSetting = that.$store.state.SelectPickerSetting;
			console.log(selectPickerSetting);
			that.sql = selectPickerSetting.sql;
			that.chooseType = selectPickerSetting.chooseType;
			that.showSearch = selectPickerSetting.showSearch;
			that.searchKey = selectPickerSetting.searchKey;
			that.displayValue = selectPickerSetting.displayValue;
			that.hiddenValue = selectPickerSetting.hiddenValue;
			that.parentValue = selectPickerSetting.parentValue;
			that.filterData = selectPickerSetting.param;
			that.pageParam = selectPickerSetting;
			that.treeQuery = '1=1';
			that.treeDataSource = selectPickerSetting.treeObj.treeDataSource
			that.treeDisplayValue = selectPickerSetting.treeObj.treeDisplayValue;
			that.treeHiddenValue = selectPickerSetting.treeObj.treeHiddenValue;
			that.treeParentValues = selectPickerSetting.treeObj.treeParentValues;
			that.filterSQL = selectPickerSetting.filterSQL;
			that.formSQL = selectPickerSetting.formSQL;
			if (that.treeDataSource) {
				await that.getLeftInfo();
			}
			await this.getSearchList(1, 20)
		},
		computed: {},
		mounted() {},
		onUnload() {
			// 关闭页面时，清除vuex中的参数数据
			this.$store.commit('ChangeAndSetStateData', {
				Name1: 'SelectPickerSetting',
				data: {}
			})
		},
		methods: {
			getLeftInfo() {
				var that = this;
				that.Request.requestByUrl('/SQLData/GetDataBySql', {
					sql: that.treeDataSource,
					sqlParam: {}
				}, function(data) {
					var list = data.ds;
					list.map(item => {
						return item.label = item[that.treeDisplayValue], item.id = item[that
							.treeHiddenValue];
					})
					console.log(list);
					that.expandNodes = list.map(item => {
						return item.id;
					});
					var newList = that.tranList(list, 0);
					console.log(that.expandNodes);
					console.log(newList);
					that.treeData = newList;
				});
			},
			tranList(list, rootVal) {
				var that = this;
				var childItem = [];
				for (var i = 0; i < list.length; i++) {
					var childObj = {}
					if (list[i][that.treeParentValues] === rootVal) {
						childObj = list[i];
						childObj.children = that.tranList(list, list[i][that.treeHiddenValue]);
						childItem.push(childObj);
					}
				}
				return childItem;
			},
			SearchOrAdd() { // 点击搜索框右侧控件 搜索 / 新增
				// 如果是允许新增
				if (this.AllowAddEdit) {
					let Name = this.pageParam.IsAllowAddEdit;
					let url = '';

					if (Name == '作业员') {
						url = 'operator_AddorEdit'
					}

					uni.navigateTo({
						url: '/AddBaseData/' + url + '?Type=add'
					})
				} else {
					// this.GetSearchList(1, 30);
					this.search();
				}
			},
			search() {
				this.$refs.paging.reload();

			},
			getSearchList(pageNo, pageSize) {
				var that = this;
				var sql = '';

				var filterQuerySql = " and 1=1 ";
				// if(that.filterSQL){
				// 	filterQuerySql+=" and " + that.filterSQL;
				// }
				if (that.formSQL) {
					filterQuerySql += " and " + that.formSQL;
				}

				if (that.sql.toLowerCase().indexOf('row_number') < 0) {
					sql = "select top " + pageSize + " * from ( SELECT row_number() over(  order by " +
						that.hiddenValue + " ) as _rownumber ,* FROM (" + that.sql + ")t where " + that.searchKey +
						" like '%" + that.filterData[that.searchKey] + "%' and " + that.treeQuery + filterQuerySql +
						" ) A where _rownumber > " + ((pageNo - 1) * pageSize)
						.toString() + ""

					sql += " select count(1) as count FROM (" + that.sql + ")t where " + that.searchKey +
						" like '%" + that.filterData[that.searchKey] + "%' and " + that.treeQuery + filterQuerySql;

				} else {
					sql = "select * from (" + that.sql + ") t where " + that.searchKey + " like '%" + that.filterData[that
						.searchKey] + "%' and " + that.treeQuery + filterQuerySql + " ";
					sql += " select count(1) as count from (" + that.sql + ") t where " + that.searchKey + " like '%" +
						that.filterData[that
							.searchKey] + "%' and " + that.treeQuery + filterQuerySql;
				}

				that.Request.requestByUrl('/SQLData/QuerySql', Object.assign({
					sql: sql
				}, that.filterData), function(data) {
					const totalCount = data.ds1[0]["count"];
					that.$refs.paging.completeByTotal(data.ds, totalCount);
				});

			},
			ChoiceCell(data) { // 选中单元格
				var that = this;
				//判断是否是单选
				if (that.chooseType == 1) {
					uni.$emit(that.pickerListen, {
						colName: that.pageParam.colName,
						msg: '',
						data: data
					});
					uni.navigateBack();
				}
			},
			openChooseType() {
				this.$refs.nextTreeAsyncRef.showTree = true;
			},
			onTreeConfirm(list) {
				var that = this;
				console.log(list);
				var selectList = list.map(function(item) {
					return item[that.treeHiddenValue];
				});

				var selectNameList = list.map(function(item) {
					return item[that.treeDisplayValue];
				});
				if (selectNameList.length > 0) {
					that.typeName = selectNameList.join(',');
				} else {
					that.typeName = "分类筛选";
				}

				if (selectList.length > 0) {
					that.treeQuery = that.parentValue + ' in ( ' + selectList.join(',') + ' )';
				} else {
					that.treeQuery = '1=1';
				}
				// that.getSearchList(1, 30);
				that.search();
			}
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f9f9f9;

		.SearchBox {
			background-color: #fff;
			background-color: #51d0d0;
			padding: 6px 10px;
		}

		.MainBox {
			flex: 1;
			overflow: auto;
		}
	}
</style>